﻿package yii{

	import yii.*;
	import phpas3.*;
	import flash.data.*;
	import flash.errors.*;
	import flash.net.*;
	import flash.utils.*;
	import flash.filesystem.*;

	public class PDO{

		private var _nativeConnection:SQLConnection;

		static public const ATTR_EMULATE_PREPARES:int = 1;
		static public const ATTR_DRIVER_NAME:int = 2;
		static public const FETCH_ASSOC:int = 3;
		static public const ATTR_ERRMODE:int = 4;
		static public const ERRMODE_EXCEPTION:int = 5;
		static public const PARAM_STR:int = 6;
		static public const PARAM_BOOL:int = 7;
		static public const PARAM_INT:int = 8;
		static public const PARAM_NULL:int = 9;
		static public const FETCH_ORI_NEXT:int = 10;




		public function get nativeConnection():SQLConnection{
			return _nativeConnection;
		}



		public function PDO( dsn:String, username:String, password:String, driver_options:Array=null ){
			// flash ネイティブの SQLConnection を作成
			_nativeConnection = new SQLConnection();
			
			trace( "PDO::constructor dsn="+ dsn );
			var dbFile:File = new File( dsn );
			trace( "DBファイルのパスは"+ dbFile.url );
			
			// ディレクトリ作成
//			var targetParent:File = dbFile.parent;
//			if( targetParent.isDirectory ){
//				targetParent.createDirectory();
//			}

			try {
				if( password ){
					Yii.log( dbFile.url +" にパスワード付きで接続します..." );
					var pass_ba:ByteArray = new ByteArray();
					pass_ba.writeUTFBytes( password );
			 	   _nativeConnection.open( dbFile, "create", false, 1024, pass_ba );
			 	} else {
					Yii.log( dbFile.url +" にパスワード無しで接続します..." );
			 	   _nativeConnection.open( dbFile );
			 	}
			    Yii.log( dbFile.url +" に接続しました。" );
			} catch (error:SQLError) {
				throw error;
			}
		}


		// 文を実行する準備を行い、文オブジェクトを返す
		public function prepare( statement_str:String, driver_options:Array=null ):PDOStatement{
			var stmt:PDOStatement = new PDOStatement( _nativeConnection, statement_str );
			return stmt;
		}




		public function lastInsertId( name:String=null ):int{
			return _nativeConnection.lastInsertRowID;
		}


		public function quote( string:String ):String{
			return "'"+ addcslashes(str_replace("'", "''", string), "\000\n\r\\\032") +"'";
		}


		public function setAttribute( attribute:int, value:* ):Boolean{
			return true;
		}



		public function exec( statement:String ):uint{
			var createStmt:SQLStatement = new SQLStatement();
			createStmt.sqlConnection = _nativeConnection;
			createStmt.text = statement;
			try {
			    createStmt.execute();
			    var result:SQLResult = createStmt.getResult();
			    return result.rowsAffected;
			} catch (error:SQLError) {
				throw error;
			}
			return null;
		}





	}
}